package org.xiaojl.xcloud.tools.gateway.filter.route;

import java.util.Arrays;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.xiaojl.xcloud.tools.gateway.RpcResult;
import org.xiaojl.xcloud.tools.gateway.config.DownGradeProperties;
import org.xiaojl.xcloud.tools.gateway.kit.FilterKit;
import org.xiaojl.xcloud.tools.gateway.kit.JsonKit;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

/**  
 * <p>Title: DowngradeFilter</p>  
 *
 * <p>Description: 服务降级过滤器</p>  
 *
 * @author jilong.xiao  
 * @date 2018年5月7日  
 */
@Component
public class DowngradeFilter extends ZuulFilter {
	private static final Logger log = LoggerFactory.getLogger(DowngradeFilter.class);
	@Autowired
	private DownGradeProperties downGradeProperties;
	
	@Override
	public boolean shouldFilter() {
		return FilterKit.isFilterFlag(RequestContext.getCurrentContext());
	}

	@Override
	public Object run() {
		RequestContext context = RequestContext.getCurrentContext();
		Object serviceId = context.get("serviceId");
		
		String downGradeServiceIds = downGradeProperties.getServiceIds();
		if(log.isDebugEnabled() && downGradeServiceIds!=null && !"".equals(downGradeServiceIds.trim())){
			log.debug(String.format("开启【降级】功能的服务：%s", downGradeServiceIds));
		}
		if(downGradeServiceIds!=null && !"".equals(downGradeServiceIds)){
			String[] serviceIds = downGradeServiceIds.split(",");
			if(Arrays.asList(serviceIds).contains(serviceId)){
				if(log.isDebugEnabled()){
					log.debug(String.format("服务[%s]正在降级中...", serviceId));
				}
				
				RpcResult result = RpcResult.fail("服务降级中", "服务["+serviceId+"]正在降级中", null);
				context.setSendZuulResponse(false);// 过滤该请求，不对其进行路由
				context.setResponseStatusCode(500);// 返回错误码  
				FilterKit.setFilterFlag(context,false);
				FilterKit.setRespBody(context,  JsonKit.toJson(result));
	            return null; 
			}
		}
		
		return null;
	}

	@Override
	public String filterType() {
		return FilterConstants.ROUTE_TYPE;
	}

	@Override
	public int filterOrder() {
		return 4;
	}

}
